package com.juyu.miliao.api.dao.redis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.constant.HostRecentDevelopmentsRedisKey;
import com.juyu.miliao.common.domain.vo.HostRecentDevelopmentsFindDynamicVO;
import com.juyu.miliao.common.domain.vo.HostRecentDevelopmentsPhotoVO;
import com.juyu.miliao.common.domain.vo.HostRecentDevelopmentsVideoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xuanqicheng
 */
@Component
public class HostRecentDevelopmentsRedisDao {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    public List<Object> getList(Long userId) throws IOException {
        List<Object> resultList = new ArrayList<>();
        String key = HostRecentDevelopmentsRedisKey.getHostRecentDevelopmentsKey(userId);
        List<String> list = stringRedisTemplate.opsForList().range(key, 0, 2);
        for(String str : list){
            JSONObject json = JSONObject.parseObject(str);
            int type = json.getIntValue("type");
            if(type==1){
                HostRecentDevelopmentsFindDynamicVO vo = objectMapper.readValue(str,
                        HostRecentDevelopmentsFindDynamicVO.class);
                resultList.add(vo);
            }else if(type == 2){
                HostRecentDevelopmentsPhotoVO vo = objectMapper.readValue(str,HostRecentDevelopmentsPhotoVO.class);
                resultList.add(vo);
            }else if(type == 3){
                HostRecentDevelopmentsVideoVO vo = objectMapper.readValue(str,HostRecentDevelopmentsVideoVO.class);
                resultList.add(vo);
            }
        }
        return resultList;
    }

    /**
     * 检查key 是否存在
     * @param userId
     * @return true 存在，false 不存在
     */
    public boolean existKey(long userId){
        String key = HostRecentDevelopmentsRedisKey.getHostRecentDevelopmentsKey(userId);
        boolean bl = stringRedisTemplate.hasKey(key);
        return bl;
    }

    public void  delete(long userId){
        String key = HostRecentDevelopmentsRedisKey.getHostRecentDevelopmentsKey(userId);
        stringRedisTemplate.delete(key);
    }
}
